
package inc.gome.dynamic.datasource.lock.store.file;

import inc.gome.dynamic.datasource.loader.LoadLevel;
import inc.gome.dynamic.datasource.lock.Locker;
import inc.gome.dynamic.datasource.lock.exception.TransactionException;
import inc.gome.dynamic.datasource.lock.manager.AbstractLockManager;
import inc.gome.dynamic.datasource.lock.session.BranchSession;
import inc.gome.dynamic.datasource.lock.session.GlobalSession;
import org.slf4j.MDC;

import java.util.ArrayList;

import static inc.gome.dynamic.datasource.lock.constant.RootContext.MDC_KEY_BRANCH_ID;


/**
 * The type file lock manager.
 *
 * @author zhangsen
 */
@LoadLevel(name = "file")
public class FileLockManager extends AbstractLockManager {

    @Override
    public Locker getLocker(BranchSession branchSession) {
        return new FileLocker(branchSession);
    }

    @Override
    public boolean releaseGlobalSessionLock(GlobalSession globalSession) throws TransactionException {
        System.out.println("释放file全局锁==》"+ globalSession.getXid());
        ArrayList<BranchSession> branchSessions = globalSession.getBranchSessions();
        boolean releaseLockResult = true;
        for (BranchSession branchSession : branchSessions) {
            try {
                MDC.put(MDC_KEY_BRANCH_ID , String.valueOf(branchSession.getBranchId()));
                if (!this.releaseLock(branchSession)) {
                    releaseLockResult = false;
                }
            } finally {
                MDC.remove(MDC_KEY_BRANCH_ID);
            }
        }
        return releaseLockResult;
    }

}
